<?php

class FileUpload {

    private $keyname = "APC_UPLOAD_PROGRESS";
    public $id;
    public $finished;
    public $percent;
    public $total;
    public $complete;
    public $fileSizeLimit;
    public $allowedFileType;

    public function __construct() {
        $config = Vega_App::getInstance()->coreConfig;
        $this->fileSizeLimit = $config['upload']['allowed_size_limit'];
        $this->allowedFileType = $config['upload']['allowed_file_type'];
    }

    public function canGetStatus() {
        if (!extension_loaded('apc') || !function_exists('apc_fetch'))
            return false;

        return ini_get('apc.enabled') && ini_get('apc.rfc1867');
    }

    public function getStatus($id, $field = 'myfile') {
        $error = 0;
        $msg = "";
        $ret = array(
            'id' => $id,
            'finished' => false,
            'percent' => 0,
            'total' => 0,
            'complete' => 0,
            'speed' => 0,
            'duration' => 0,
            'remaining' => 0,
        );

        // retrieve the upload data from APC
        $status = apc_fetch("upload_" . $id);

        // false is returned if the data isn't found
        if ($status) {
            $ret['finished'] = (bool) $status['done'];
            $ret['total'] = $status['total'];
            $ret['complete'] = $status['current'];

            // calculate the average speed in Kb
            $ret['speed'] = round($status['current'] / (time() - $status['start_time']) / 1024);

            // calculate the completed percentage
            $ret['percent'] = ($ret['total'] > 0) ? round($ret['complete'] / $ret['total'] * 100) : 0;

            $ret['duration'] = $this->_parseTime(round(time() - $status['start_time']));
            $ret['remaining'] = $this->_parseTime(round(($status['total'] - $status['current']) / ($status['current'] / (time() - $status['start_time']))));
        }
		$typeInfo = true;
		if ($ret['percent'] == 100) {
			$ext = $this->_getFileExtension($status['filename']);
			$filesource = "/mobitv_src/file_src/$id.$ext";
			$typeInfo = $this->validateFileInfo($filesource);
			if (!$typeInfo) $error = 1;
		}
        return array('error' => $error, 'msg' => $msg, 'data' => $ret, 'typeInfo' => $typeInfo);
    }

    public function validateFileInfo($myFile) {
        $oFileInfo = new finfo(FILEINFO_MIME_TYPE);
        $sMimeType = $oFileInfo->file($myFile);
        $arr_type = explode("/", $sMimeType);
        $arr_TypeValid = array('video', 'audio', 'image', 'application');
        if (!in_array($arr_type[0], $arr_TypeValid)) {
            return false;
        }
        return true;
    }

    public function validate($id, $field) {
        // sanitize the ID value
        $id = preg_replace('/[^a-z0-9]/i', '', $id);
        if (strlen($id) == 0)
            return array('error' => 1, 'msg' => 'ID không hợp lệ!');

        $error = 0;
        $msg = "File hợp lệ, bắt đầu upload";

        // if we can't retrieve the status or the upload has finished just return
        if (!$this->canGetStatus())
            return array('error' => 1, 'msg' => 'Hãy kiểm tra lại cấu hình hệ thống!');

        // retrieve the upload data from APC
        $status = apc_fetch("upload_" . $id);

        // false is returned if the data isn't found
        if ($status) {
            // validate
            $ext = $this->_getFileExtension($status['filename']);
            if (!in_array($ext, explode(",", $this->allowedFileType))) {
                $error = 1;
                $msg = "Định dạng file không hợp lệ!";
                return array('error' => 1, 'msg' => 'Định dạng file không hợp lệ!');
            }

            if ($status['total'] > $this->fileSizeLimit * 1024 * 1024) {
                return array('error' => 1, 'msg' => 'Kích thước file quá giới hạn cho phép!');
            }
        } else {
            return array('error' => 0, 'msg' => 'Không lấy được trạng thái hoặc kích thước file quá lớn!');
        }

        return array('error' => $error, 'msg' => $msg);
    }

    public function upload($id, $field, $path) {
        // ensure the given file has been uploaded
        if (!isset($_FILES[$field]) || !is_array($_FILES[$field]))
            return false;

        $file = $_FILES[$field];
        // only proceed if no errors have occurred
        if ($file['error'] != UPLOAD_ERR_OK) {
            //echo $_FILES[$field]['error'];
            return false;
        }

        $ext = $this->_getFileExtension($file['name']);
        $filename = $id . "." . $ext;
        // write the uploaded file to the filesystem
        $fullpath = sprintf('%s/%s', $path, $filename);
        if (!move_uploaded_file($file['tmp_name'], $fullpath))
            return false;

        return $filename;
    }

    public function setFileSizeLimit($limit) {
        if ($limit)
            $this->fileSizeLimit = $limit;
    }

    public function getId() {
        return $this->id;
    }

    public function getKeyname() {
        return $this->keyname;
    }

    public function generateKey() {
        return date("YmdHis") . rand(100, 999);
    }

    public function getFilename($id, $file) {
        $ext = $this->_getFileExtension($file['name']);
        $filename = $id . "." . $ext;

        return $filename;
    }

    private function _getFileExtension($filename) {
        $info = pathinfo($filename);

        return $info['extension'];
    }

    private function _parseTime($second) {
        if (!is_numeric($second))
            return $second;
        $second = intval($second);

        $hour = intval($second / 3600);
        if ($hour < 10)
            $hour = '0' . $hour;
        $second = $second % 3600;
        $minute = intval($second / 60);
        if ($minute < 10)
            $minute = '0' . $minute;
        $second = intval($second % 60);
        if ($second < 10)
            $second = '0' . $second;
        return $hour . ":" . $minute . ":" . $second;
    }

}
